import axios from 'axios';
import {
  jsonlint
} from '@/utils/jsonlint';
import {
  message
} from 'antd';
import {
  history
} from 'umi';
import defaultSetting from '@/../config/defaultSettings';
import isPlainObject from 'lodash/isPlainObject';
const request = axios.create({
  baseURL: defaultSetting.baseUrl,
  timeout: 1000 * 600,
  withCredentials: false,
  transformResponse: [
    function (data) {
      if (
        data.type === 'application/vnd.ms-excel' ||
        data.type === `image/gif` ||
        data.type === `text/xml`
      ) {
        return data;
      } else {
        try {
          const payload = jsonlint.parse(data);
          const {
            status
          } = payload;
          if (status === 401) {
            sessionStorage.removeItem('token');
            message.error('账号已在其他地方登陆或登录已过期');
            setTimeout(() => {
              history.push('/user/login');
            }, 1200);
          }
          return jsonlint.parse(data);
        } catch (error) {
          // return jsonlint.parse(data);
          return data;
        }
      }
    },
  ],
});


request.interceptors.request.use(
  (config) => {
    config.headers.token = sessionStorage.getItem('token') || '';
    config.headers['responseType'] = config.responseType || '';
    config.headers.type = 'ADMIN';
    var defaults = {};
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        ...{
          _t: new Date().getTime()
        },
      };
    }
    if (isPlainObject(config.params)) {
      config.params = {
        ...defaults,
        ...config.params,
      };
      for (let index in config.params) {
        if (!!!config.params[index]) {
          delete config.params[index];
        }
      }
    }
    if (isPlainObject(config.data)) {
      config.data = {
        ...defaults,
        ...config.data,
      };
      if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
        config.data = qs.stringify(config.data);
      }
    }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  },
);
/**
 * 响应拦截
 */

request.interceptors.response.use(
  (response) => {
    const {
      data: {
        type,
        code
      },
      status,
    } = response;
    if (code && code != 0) {
      message.error(response.data.message);
      return;
    }

    if (type === 'image/gif') {
      return response;
    } else {
      return response.data;
    }
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default request;
